package com.luo.backend.controller;

import com.luo.backend.common.ApiResponse;
import com.luo.backend.dto.AddressRequest;
import com.luo.backend.dto.AddressResponse;
import com.luo.backend.service.AddressService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 地址管理控制器
 */
@RestController
@RequestMapping("/api/v1/user/addresses")
public class AddressController {
    
    private static final Logger logger = LoggerFactory.getLogger(AddressController.class);
    
    @Autowired
    private AddressService addressService;
    
    /**
     * 获取用户地址列表
     */
    @GetMapping
    public ApiResponse<List<AddressResponse>> getAddresses() {
        try {
            Long userId = getCurrentUserId();
            List<AddressResponse> addresses = addressService.getUserAddresses(userId);
            return ApiResponse.success(addresses);
        } catch (Exception e) {
            logger.error("获取地址列表失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 添加收货地址
     */
    @PostMapping
    public ApiResponse<AddressResponse> addAddress(@Valid @RequestBody AddressRequest request) {
        try {
            Long userId = getCurrentUserId();
            AddressResponse address = addressService.addAddress(userId, request);
            return ApiResponse.created("地址添加成功", address);
        } catch (Exception e) {
            logger.error("添加地址失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 更新收货地址
     */
    @PutMapping("/{id}")
    public ApiResponse<AddressResponse> updateAddress(
            @PathVariable Long id,
            @Valid @RequestBody AddressRequest request) {
        try {
            Long userId = getCurrentUserId();
            AddressResponse address = addressService.updateAddress(userId, id, request);
            return ApiResponse.success("地址更新成功", address);
        } catch (Exception e) {
            logger.error("更新地址失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 删除收货地址
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteAddress(@PathVariable Long id) {
        try {
            Long userId = getCurrentUserId();
            addressService.deleteAddress(userId, id);
            return ApiResponse.success("地址删除成功", null);
        } catch (Exception e) {
            logger.error("删除地址失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 设置默认地址
     */
    @PutMapping("/{id}/default")
    public ApiResponse<AddressResponse> setDefaultAddress(@PathVariable Long id) {
        try {
            Long userId = getCurrentUserId();
            AddressResponse address = addressService.setDefaultAddress(userId, id);
            return ApiResponse.success("默认地址设置成功", address);
        } catch (Exception e) {
            logger.error("设置默认地址失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取默认地址
     */
    @GetMapping("/default")
    public ApiResponse<AddressResponse> getDefaultAddress() {
        try {
            Long userId = getCurrentUserId();
            AddressResponse address = addressService.getDefaultAddress(userId);
            return ApiResponse.success(address);
        } catch (Exception e) {
            logger.error("获取默认地址失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof Long) {
            return (Long) principal;
        }
        throw new RuntimeException("未能获取当前用户信息");
    }
}

